package com.platform.boot.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.platform.boot.annotation.ReactiveUserAuditorAware;
import com.platform.boot.annotation.UserAuditor;
import com.platform.boot.security.SecurityUserManager;
import com.platform.boot.security.filter.AfterSecurityFilter;
import com.platform.boot.security.filter.BeforeSecurityFilter;
import com.platform.boot.security.filter.ExchangeContextFilter;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.ReactiveAuditorAware;
import org.springframework.data.web.ReactivePageableHandlerMethodArgumentResolver;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;

import java.time.format.DateTimeFormatter;

/**
 * @author Alex bob(<a href="https://github.com/vnobo">https://github.com/vnobo</a>)x
 */
@Configuration(proxyBeanMethods = false)
public class WebConfiguration implements WebFluxConfigurer {

    @Override
    public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
        ReactivePageableHandlerMethodArgumentResolver argumentResolver =
                new ReactivePageableHandlerMethodArgumentResolver();
        argumentResolver.setMaxPageSize(10000);
        configurer.addCustomResolver(argumentResolver);
    }

    @Bean
    public AfterSecurityFilter afterSecurityFilter() {
        return new AfterSecurityFilter();
    }

    @Bean
    public BeforeSecurityFilter beforeSecurityFilter(SecurityUserManager userManager) {
        return new BeforeSecurityFilter(userManager);

    }

    @Bean
    public ExchangeContextFilter exchangeContextFilter() {
        return new ExchangeContextFilter();
    }

    @Bean
    public ReactiveAuditorAware<UserAuditor> creatorsAuditorProvider() {
        return new ReactiveUserAuditorAware();
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat("yyyy-MM-dd");
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        };
    }
}